#include "mainwindow.h"
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QPainter>
#include <QRandomGenerator>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), cellSize(0)
{
    int mapSize = 100;  // 地图大小
    cellSize = 10;  // 单元格大小

    QString mapFilePath = "map.map";
    // 先生成并保存地图文件
    generateAndSaveMap(mapFilePath);
    // 再从文件加载地图数据
    loadMapData(mapFilePath);

    // 根据地图数据大小和单元格大小设置窗口大小
    setFixedSize(mapData.size() * cellSize, mapData.size() * cellSize);
}

MainWindow::~MainWindow()
{
}

// 生成地图数据并保存为.map文件
void MainWindow::generateAndSaveMap(const QString& filePath) {
    int mapSize = 100;
    QVector<QVector<MapElement>> fixedMapData(mapSize, QVector<MapElement>(mapSize, MapElement::Empty));
    int centerX = mapSize / 2;
    int centerY = mapSize / 2;

    // 计算平移后的中心坐标，先上移5个单位，再上移7个单位，共上移12个单位
    centerY -= 12;

    // 绘制“中”字形状的障碍物
    // 竖线
    for (int y = centerY - 15; y <= centerY + 15; ++y) {
        for (int x = centerX - 1; x <= centerX + 1; ++x) {
            fixedMapData[y][x] = MapElement::Obstacle;
        }
    }
    // 上面的横线
    for (int x = centerX - 7; x <= centerX + 7; ++x) {
        for (int y = centerY - 15; y <= centerY - 13; ++y) {
            fixedMapData[y][x] = MapElement::Obstacle;
        }
    }
    // 下面的横线
    for (int x = centerX - 7; x <= centerX + 7; ++x) {
        for (int y = centerY + 13; y <= centerY + 15; ++y) {
            fixedMapData[y][x] = MapElement::Obstacle;
        }
    }

    // 在“中”字上方绘制半圆
    int radius = 10;
    for (int y = centerY - 15 - radius; y <= centerY - 15; ++y) {
        for (int x = centerX - radius; x <= centerX + radius; ++x) {
            int dx = x - centerX;
            int dy = y - (centerY - 15);
            if (dx * dx + dy * dy <= radius * radius) {
                fixedMapData[y][x] = MapElement::Obstacle;
            }
        }
    }

    // 在“中”字下方绘制小车
    // 车身
    int carWidth = 28;   // 原来56，缩小一半
    int carHeight = 12;  // 原来24，缩小一半
    int carX = centerX - carWidth / 2;
    int carY = centerY + 15 + 5; // 在“中”字下方适当位置
    for (int y = carY; y < carY + carHeight; ++y) {
        for (int x = carX; x < carX + carWidth; ++x) {
            fixedMapData[y][x] = MapElement::Obstacle;
        }
    }
    // 车轮
    int wheelRadius = 6;  // 原来12，缩小一半
    for (int y = carY + carHeight - wheelRadius; y <= carY + carHeight; ++y) {
        for (int x = carX + wheelRadius; x < carX + 2 * wheelRadius; ++x) {
            int dx = x - (carX + wheelRadius);
            int dy = y - (carY + carHeight);
            if (dx * dx + dy * dy <= wheelRadius * wheelRadius) {
                fixedMapData[y][x] = MapElement::Obstacle;
            }
        }
        for (int x = carX + carWidth - 2 * wheelRadius; x < carX + carWidth - wheelRadius; ++x) {
            int dx = x - (carX + carWidth - wheelRadius);
            int dy = y - (carY + carHeight);
            if (dx * dx + dy * dy <= wheelRadius * wheelRadius) {
                fixedMapData[y][x] = MapElement::Obstacle;
            }
        }
    }

    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        for (const auto& row : fixedMapData) {
            for (const auto& element : row) {
                if (element == MapElement::Empty) {
                    out << '0';
                } else {
                    out << '1';
                }
            }
            out << '\n';
        }
        file.close();
    } else {
        qDebug() << "无法打开文件进行写入: " << filePath;
    }
}

// 从.map文件加载地图数据
void MainWindow::loadMapData(const QString& filePath) {
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        int row = 0;
        while (!in.atEnd()) {
            QString line = in.readLine();
            QVector<MapElement> rowData;
            for (QChar ch : line) {
                if (ch == '0') {
                    rowData.append(MapElement::Empty);
                } else if (ch == '1') {
                    rowData.append(MapElement::Obstacle);
                }
            }
            mapData.append(rowData);
            row++;
        }
        file.close();
    } else {
        qDebug() << "无法打开地图文件: " << filePath;
    }
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    int mapSize = mapData.size();
    int randomRow1, randomCol1, randomRow2, randomCol2;

    // 随机选取第一个点，确保不在障碍物上
    do {
        randomRow1 = QRandomGenerator::global()->bounded(mapSize);
        randomCol1 = QRandomGenerator::global()->bounded(mapSize);
    } while (mapData[randomRow1][randomCol1] == MapElement::Obstacle);

    // 随机选取第二个点，确保不在障碍物上且与第一个点不同
    do {
        randomRow2 = QRandomGenerator::global()->bounded(mapSize);
        randomCol2 = QRandomGenerator::global()->bounded(mapSize);
    } while (mapData[randomRow2][randomCol2] == MapElement::Obstacle || (randomRow1 == randomRow2 && randomCol1 == randomCol2));

    // 计算两个点的坐标
    QPointF point1(randomCol1 * cellSize + cellSize / 2, randomRow1 * cellSize + cellSize / 2);
    QPointF point2(randomCol2 * cellSize + cellSize / 2, randomRow2 * cellSize + cellSize / 2);

    // 计算控制点（这里简单取两点中点作为控制点）
    QPointF controlPoint((point1.x() + point2.x()) / 2, (point1.y() + point2.y()) / 2);

    // 再绘制地图
    QPen blackPen(Qt::black);  // 创建黑色画笔用于绘制网格
    painter.setPen(blackPen);
    for (int i = 0; i < mapData.size(); ++i) {
        for (int j = 0; j < mapData[i].size(); ++j) {
            if (mapData[i][j] == MapElement::Empty) {
                if (i == randomRow1 && j == randomCol1) {
                    painter.fillRect(j * cellSize, i * cellSize, cellSize, cellSize, Qt::blue);
                } else if (i == randomRow2 && j == randomCol2) {
                    painter.fillRect(j * cellSize, i * cellSize, cellSize, cellSize, Qt::green);
                } else {
                    painter.fillRect(j * cellSize, i * cellSize, cellSize, cellSize, Qt::white);
                }
            } else {
                painter.fillRect(j * cellSize, i * cellSize, cellSize, cellSize, Qt::black);
            }
            painter.drawRect(j * cellSize, i * cellSize, cellSize, cellSize);
        }
    }

    // 绘制黄色的线连接两个点
    QPen yellowPen(Qt::yellow);
    yellowPen.setWidth(2);
    painter.setPen(yellowPen);
    painter.drawLine(point1, point2);

    qDebug() << "paintEvent 被调用";
}
